﻿using AdminBase.Common.Attributes;
using AdminBase.Common.Helpers;
using AdminBase.Interface;
using AdminBase.Model;
using AdminBase.Model.Common;
using AdminBase.Model.Entitys;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace AdminBase.webapi.Controllers
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    [ApiController]
    [Authorize]
    [Route("[controller]")]
    [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
    [TypeFilter(typeof(AsyncExceptionFilterAttribute))]
    public class UsersController : ControllerBase
    {
        private readonly IUsersService _users;
        // 文件业务接口
        private readonly IFilesService _fileService;
        // 静态文件夹接口
        private readonly IWebHostEnvironment _environment;

        /// <summary>
        /// 构造函数注册
        /// </summary>
        /// <param name="Users"></param>
        /// <param name="environment"></param>
        /// <param name="fileService"></param>
        public UsersController(IUsersService Users, IWebHostEnvironment environment, IFilesService fileService)
        {
            _users = Users;
            _environment = environment;
            _fileService = fileService;
        }

        /// <summary>
        /// 获取单个用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{id:long}")]
        public ApiResult GetUser(long id)
        {
            var usersDto = _users.GetUser(id: id);
            if (usersDto == null)
            {
                return ResultHelper.Error("用户不存在");
            }
            // 获取角色
            var roles = _users.GetRolesByUserId(usersDto.ID);
            if (roles.Any())
            {
                usersDto.Roles = roles.Select(u => u.ID).ToList();
                usersDto.RolesName = roles.Select(u => u.Name).ToList();
            }
            return ResultHelper.Success(usersDto);
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="queryParam">查询参数</param>
        /// <param name="pageBase">分页查询</param>
        /// <returns></returns>
        [HttpGet]
        public ApiResult GetUsers([FromQuery] UsersQueryParam queryParam, [FromQuery] PageBase pageBase)
        {
            return ResultHelper.Success(_users.GetUsers(queryParam, pageBase));
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult Add(UsersDto user)
        {
            user.UserName = user.UserName.Trim();
            // 判断用户是否已存在
            var entity = _users.Exists(user.UserName);
            if (entity)
            {
                return ResultHelper.Error($"已存在账号为{user.UserName}的用户");
            }
            //获取当前登录人信息 
            string userName = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "UserName")?.Value;
            user.CreateUserName = userName;
            user.UpdateUserName = userName;
            return ResultHelper.Success(_users.Add(user), $"用户{user.UserName}添加成功");
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPut]
        public ApiResult Update(UsersDto user)
        {
            //获取当前登录人信息 
            string userName = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "UserName")?.Value;
            user.UpdateUserName = userName;
            return ResultHelper.Success(_users.Edit(user), $"用户{user.UserName}修改成功");
        }

        /// <summary>
        /// 修改个人信息：姓名、手机号、邮箱
        /// </summary>
        /// <param name="users"></param>
        /// <returns></returns>
        [HttpPatch]
        public ApiResult UpdateInfo(Users user)
        {
            var id = long.Parse(HttpContext.User.Claims.FirstOrDefault(c => c.Type == "ID")?.Value);
            var entity = _users.GetUser(id: id);
            if (entity == null)
            {
                return ResultHelper.Error("用户不存在");
            }
            entity.FullName = user.FullName;
            entity.Mobile = user.Mobile;
            entity.Email = user.Email;
            return ResultHelper.Success(_users.Edit(entity, info: true));
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        [Route("{id}")]
        public ApiResult Del(long id)
        {
            return ResultHelper.Success(_users.Del(id));
        }

        /// <summary>
        /// 批量删除用户
        /// </summary>
        /// <param name="ids">ids</param>
        /// <returns></returns>
        [HttpDelete]
        public ApiResult BatchDel([FromBody] List<long> ids)
        {
            return ResultHelper.Success(_users.BatchDel(ids));
        }

        /// <summary>
        /// 修改激活状态
        /// </summary>
        /// <param name="users"></param>
        /// <returns></returns>
        [HttpPatch]
        [Route("active")]
        public ApiResult UpdateActive(Users users)
        {
            return ResultHelper.Success(_users.UpdateActive(users));
        }

        /// <summary>
        /// 设置密码
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("pwd")]
        public ApiResult SetPassword(PasswordDto password)
        {
            return ResultHelper.Success(_users.SetPassword(password));
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPut]
        [Route("pwd")]
        public ApiResult UpdatePassword(PasswordDto password)
        {
            password.ID = long.Parse(HttpContext.User.Claims.FirstOrDefault(c => c.Type == "ID")?.Value);
            if (!password.ID.HasValue)
            {
                return ResultHelper.Error("请先登录");
            }

            if (string.IsNullOrWhiteSpace(password.Password) || string.IsNullOrWhiteSpace(password.ConfirmPassword))
            {
                return ResultHelper.Error("请输入密码及确认密码");
            }
            // 根据这个账号查询
            UsersDto entity = _users.GetUser(id: password.ID);
            // 没匹配到账号
            if (entity == null || string.IsNullOrEmpty(entity.UserName))
            {
                return ResultHelper.Error("账号不存在");
            }
            // 旧密码密码验证不成功
            if (!PasswordHelper.VerifyPassword(password.OldPassword, entity.PassWord, entity.Salt))
            {
                return ResultHelper.Error("旧密码错误");
            }
            password.ID = entity.ID;
            password.Salt = entity.Salt;
            return ResultHelper.Success(_users.SetPassword(password));
        }

        /// <summary>
        /// 上传头像
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPut]
        [Route("avatar")]
        public ApiResult UploadAvatar(IFormFile image)
        {
            if (image == null)
            {
                return ResultHelper.Success("请选择文件上传!");
            }
            var fileName = image.FileName;
            if (!FilesHelper.IsMatchFormat(fileName, type: "image"))
            {
                return ResultHelper.Success("上传失败：请上传正确格式的文件!");
            }
            // 上限10M
            if (image.Length > 1024 * 1024 * 10)
            {
                return ResultHelper.Success("上传失败：文件大小不能超过10M");
            }
            if (image.Length > 0)
            {
                string userName = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "UserName")?.Value;
                // 检查或创建文件夹
                string userPath = Path.Combine("images", userName, DateTime.Now.ToString("yyyy-MM-dd"));
                string fullPath = Path.Combine(_environment.WebRootPath, userPath);
                FilesHelper.CreateDir(fullPath);

                Files entity = new Files();
                entity.FileID = Guid.NewGuid().ToString().Replace("-", "").ToLower();
                string suffix = Path.GetExtension(image.FileName);
                entity.FileName = $"{userName}-avatar{suffix}";
                string newFileName = entity.FileID + suffix;
                entity.FilePath = Path.Combine(userPath, newFileName);

                fullPath = Path.Combine(_environment.WebRootPath, entity.FilePath);
                // 保存文件
                using (var stream = System.IO.File.Create(fullPath))
                {
                    image.CopyToAsync(stream);
                }

                entity.CreateUserName = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "FullName")?.Value; // 获取当前登录人信息 
                entity.CreateDateTime = DateTime.Now;
                // 新增文件表数据
                _fileService.Add(entity);
                _users.SetAvatar(userName, entity.FileID);
                return ResultHelper.Success(entity);
            }
            return ResultHelper.Success("上传失败：文件为空");
        }
    }
}
